package com.example.app2;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.ListView;

import com.google.gson.Gson;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;
// 网络请求数据显示在ListView上
public class FoodListActivity extends AppCompatActivity {
    ListView lv;
    String url = "http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&page=1";
    List<FoodBean.DataBean> data;
    private FoodAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_food_list);
        lv = findViewById(R.id.food_lv);
        // 2.设置数据源
        data = new ArrayList<>();
        //3.设置适配器
        adapter = new FoodAdapter(this, data);
        lv.setAdapter(adapter);
        // 4.加载网络数据
        loadData();
    }
    private void loadData() {
        RequestParams params = new RequestParams(url);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                FoodBean foodBean = new Gson().fromJson(result, FoodBean.class);
                List<FoodBean.DataBean> list = foodBean.getData(); //需要的网络集合
                data.addAll(list);  //更新数据源
                adapter.notifyDataSetChanged();
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) { }
            @Override
            public void onCancelled(CancelledException cex) { }
            @Override
            public void onFinished() { }
        });
    }
}

